package com.etrans.web.gps.business.orderReceiving.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.orderReceiving.domain.Alarm;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.common.message.MailSendUtil;
import com.etrans.web.gps.common.message.SMSUtil;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.timer.LocalCache;
import com.etrans.web.gps.util.AlarmKindUtil;

@Service
public class OrderReceivingService extends BaseService{
	
	@Autowired
	private AlarmKindUtil alarmKindUtil;
	
	private Map<Integer,Object> colorMap = new HashMap<Integer,Object>();
	
	
	
	public PageVo queryTable(Map<String,Object> map) throws ParseException{
		PageVo vo = new PageVo();
		String license = map.get("license")==null?"":String.valueOf(map.get("license"));
		String alarmType = map.get("alarmType")==null?"":String.valueOf(map.get("alarmType"));
		String processType = map.get("processType")==null?"":String.valueOf(map.get("processType"));
		String startTime = (String)map.get("inputStartDate");
		String endTime = (String)map.get("inputEndDate");
		Integer pageSize = map.get("pageSize")!=null&&!"".equals(map.get("pageSize"))?(Integer)map.get("pageSize"):null;
		Integer page = map.get("page")!=null?(Integer)map.get("page"):null;
		if(pageSize==null||page==null){
			return vo;
		}
		HashMap< String,Object> whereMap = new  HashMap<String,Object>();
		if(StringUtils.isNotBlank(license)){
			whereMap.put("vehicle_no", license);
		};
		if(StringUtils.isNotBlank(alarmType)){
			whereMap.put("alarm_type", Integer.valueOf(alarmType));
		};
		if(StringUtils.isNotBlank(processType)){
			whereMap.put("alarm_src", Integer.valueOf(processType));
		};

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		HashMap<String,Object> timeMap = new HashMap<String,Object>();
		if(StringUtils.isNotBlank(startTime)){
			timeMap.put("$gte", sdf.parse(startTime + " 00:00:00"));
		}
		if(StringUtils.isNotBlank(endTime)){
			timeMap.put("$lte", sdf.parse(endTime + " 23:59:59"));
		}
		whereMap.put("alarm_time",timeMap);
 		HashMap< String,Object> sortMap= new HashMap<String,Object>();
 		sortMap.put("alarm_time",-1);
		Long count  = MGTemplete.findCount("egov", "alarm_result", whereMap);
		List<Document> dlist = MGTemplete.findDocumentsByPage("egov", "alarm_result", whereMap, sortMap,page, pageSize);
		List<Alarm> list = getAlarm(dlist);
		vo.setPage(page);
		vo.setRows(list);
		vo.setTotal(count.intValue());
		return vo;
 	}
	
	
	public Map<String,Object> saveHandleDetail(Map<String,Object> map){
		String notice_obj = null;
		Integer notice_obj1 = map.get("notice_driver")==null?null:Integer.parseInt((String)map.get("notice_driver"));
		Integer notice_obj3 = map.get("notice_principal")==null?null:Integer.parseInt((String)map.get("notice_principal"));
		Integer notice_obj4 = map.get("notice_operator")==null?null:Integer.parseInt((String)map.get("notice_operator"));
		Integer notice_obj5 = map.get("notice_organization")==null?null:Integer.parseInt((String)map.get("notice_organization"));
		notice_obj=(notice_obj1==null?"":notice_obj1+",")+/*(notice_obj2==null?"":notice_obj2+",")+*/(notice_obj3==null?"":notice_obj3+",")+(notice_obj4==null?"":notice_obj4+",")+(notice_obj5==null?"":notice_obj5);
		if(notice_obj!=null&&!"".equals(notice_obj)){
			notice_obj=notice_obj.substring(0).equals(",")?notice_obj.substring(1, notice_obj.length()-1):notice_obj;
			notice_obj=notice_obj.substring(notice_obj.length()-1).equals(",")?notice_obj.substring(0, notice_obj.length()-2):notice_obj;
		}
		map.put("notice_obj", notice_obj);
		map.put("alarm_time",map.get("alarm_time")==null?null:new Date(Long.parseLong((String)map.get("alarm_time"))));
		String tips = this.sendInform(map);
		Map<String,Object>  tipMap = new HashMap<String,Object>();
		if("success".equals(tips)){
			this.insert("orderReceivingMapper.saveHandleDetail", map);
			tipMap.put("result","success");
		}else{
			tipMap.put("result","fail");
			tipMap.put("tips",tips);
		}
		return tipMap;
	}
	
	private  List<String> queryEmailOrPhone(Map<String,Object> map,String type){
		List<String> Mblist = new ArrayList<String>();
		List<String> Emlist = new ArrayList<String>();
		Integer notice_obj1 = map.get("notice_driver")==null?null:Integer.parseInt((String)map.get("notice_driver"));
		Integer notice_obj3 = map.get("notice_principal")==null?null:Integer.parseInt((String)map.get("notice_principal"));
		Integer notice_obj4 = map.get("notice_operator")==null?null:Integer.parseInt((String)map.get("notice_operator"));
		Integer notice_obj5 = map.get("notice_organization")==null?null:Integer.parseInt((String)map.get("notice_organization"));
		List<Map<String,Object>> vlist = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> elist = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> plist = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> alist = new ArrayList<Map<String,Object>>();
		if(notice_obj1!=null){
			vlist = this.selectList("orderReceivingQuery.queryDriver",map);
		}
		if(notice_obj3!=null){
			elist = this.selectList("orderReceivingQuery.queryEnterprise",map);
		}
		if(notice_obj4!=null){
			alist = this.selectList("orderReceivingQuery.queryOrganize",map);
		}
		if(notice_obj5!=null){
			plist = this.selectList("orderReceivingQuery.queryPlatform",map);
		}
		if(elist!=null){
			for (Map<String, Object> map0 : elist) {
				Emlist.add((String)map0.get("email"));
				Mblist.add((String)map0.get("phone"));
			}
		}
		if(plist!=null){
			for (Map<String, Object> map1 : plist) {
				Emlist.add((String)map1.get("email"));
				Mblist.add((String)map1.get("phone"));
			}		
		}
		if(alist!=null){
			for (Map<String, Object> map2 : alist) {
				Emlist.add((String)map2.get("email"));
				Mblist.add((String)map2.get("phone"));
			}
		}
		if(vlist!=null){
			for (Map<String, Object> map3 : vlist) {
				Mblist.add((String)map3.get("phone"));
			}
		}
		return "phone".equals(type)?Mblist:Emlist;
	}
	
	
	
	private String sendInform(Map<String,Object> map){
		String tips = null;
		Integer type = Integer.parseInt((String)map.get("notice_type"));
		List<String> list = null;
		String msg = map.get("handle_remark")==null?"":(String)map.get("handle_remark");
		if(type==1){
			Integer DriverId = this.getDriverId(map);
			if(DriverId!=null){
				map.put("driverId",DriverId);
				map.put("message",msg);
				this.insert("orderReceivingMapper.saveAppInform",map);
				tips="success";
			}else{
				tips="处理失败，当前司机未注册APP账号！";
			}
		}else if(type==2){
			list =  queryEmailOrPhone(map,"phone");
			if(list!=null&&list.size()!=0){
				for (String phone : list) {
					SMSUtil.sendMessage(phone,"【车辆联网联控平台】"+msg,"","","");
				}
				tips="success";
			}else{
				tips="处理失败，无法获取手机号码！";
			}

		}else if(type==3){
			list =  queryEmailOrPhone(map,"Email");
			if(list!=null&&list.size()!=0){
				for (String email : list) {
					MailSendUtil.sendEmail(email, "报警处理提醒",email, "【车辆联网联控平台通知】"+msg);
				}
				tips="success";
			}else{
				tips="处理失败，无法找到邮箱地址！";
			}
		}
		return tips;
	}
	
	@SuppressWarnings("unchecked")
	private List<Alarm> getAlarm(List<Document> list){
		List<Alarm> alist = new ArrayList<Alarm>();
		if(list!=null&&list.size()>0){
			setColor();
			for (Document document : list) {
				Alarm al = MGTemplete.toBean(document, Alarm.class,true);
				Document doc = (Document)document.get("coordinates");
				List<Double> dlist = (List<Double>)doc.get("coordinates");
				al.setLng(dlist.get(0));
				al.setLat(dlist.get(1));
				if(al.getVehicle_color()!=null){
					al.setVehicle_color_name((String)colorMap.get(al.getVehicle_color()));
				}
				Map<Integer, String> emap = LocalCache.entMap;
				if(emap != null && emap.size() > 0){
					al.setEnterprise_name(emap.get(al.getEnterprise_id()));
				}
				Map<Integer, String> pmap = LocalCache.platMap;
				if(pmap != null && pmap.size() > 0){
					al.setPlatform_name(pmap.get(al.getPlatform_id()));
				}
				al.setAlarm_type_name(alarmKindUtil.getAlarmKindName(al.getAlarm_type()) );
				Map<String,Object> map = getHandleInfo(al.getVehicle_no(),al.getVehicle_color(),al.getAlarm_type(),al.getAlarm_time());
				if(map!=null){
					al.setHandle_time((Date)map.get("handle_time"));
					al.setHandle_remark(map.get("handle_remark")!=null?(String)map.get("handle_remark"):null);
					al.setHandle_type(map.get("handle_type")!=null?(Integer)map.get("handle_type"):null);
				}
				alist.add(al);
			}
		}
		return alist;
	}
	
	private Map<String,Object> getHandleInfo(String vehicle_no,Integer vehicle_color,Integer alarm_type,Date alarm_time){
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("vehicle_no", vehicle_no);
		map.put("vehicle_color", vehicle_color);
		map.put("alarm_time", alarm_time);
		map.put("alarm_type", alarm_type);
		return this.selectOne("orderReceivingQuery.queryHandleInfo", map);
	}
	
	private void setColor(){
		List<Map<String,Object>> list =this.selectList("orderReceivingQuery.queryColor",null);
		for (Map<String, Object> map : list) {
			colorMap.put((Integer)map.get("id"),map.get("name"));
		}
	}
	
	public Integer getDriverId(Map<String,Object> map){
		 String vehicle_no = map.get("vehicle_no")==null?null:(String)map.get("vehicle_no");
		 Integer vehicle_color = map.get("vehicle_color")==null?null:Integer.parseInt((String)map.get("vehicle_color"));
		HashMap<String,Object> whereMap = new  HashMap<String,Object>();
		whereMap.put("vehicle_color",vehicle_color);
		whereMap.put("vehicle_no",vehicle_no);
		String licence = null;
		List<Document> list = MGTemplete.find("egov", "driver_vehicle_swap",whereMap);
		for (Document document : list) {
			licence=(String)document.get("licence");
		}
		whereMap.put("licence",licence);
		Integer DriverId =this.selectOne("orderReceivingQuery.queryDriverId",whereMap);
		return DriverId;
	}
	
	public Map<String,Object> queryalarmhandle(Map<String,Object> map){
		return this.selectOne("orderReceivingQuery.queryalarmhandle", map);
	}
}
